package com.tiantian.framework.config.Interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.tiantian.common.core.domain.model.LoginUser;
import com.tiantian.common.helper.LoginHelper;
import com.tiantian.common.utils.ServletUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Component
public class WSHandshakeInterceptor implements HandshakeInterceptor {


    /**
     * WebSocket握手之前，若返回false，则不建立链接
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        // 从参数中获取到token
        String token = ServletUtils.getParameter("token");
        // token反查用户
        LoginUser loginUser = LoginHelper.getLoginUser(token);
        // 进行登录验证，当用户权限验证通过后，进行握手成功操作
        if (ObjectUtil.isNotEmpty(loginUser)) {
            // 将userId放到下游
            attributes.put("userId", loginUser.getUserId());
            return true;
        }
        // 验证失败返回false
        return false;
    }

    /**
     * WebSocket握手之后
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
